﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace GoodMan.Infrastructure.Entities.Repository
{
    [Table("T_ProductCategory")]
    public class T_ProductCategory : IEntity<T_ProductCategory>
    {
        [Key]
        [Column(TypeName = "int")]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Column(TypeName = "varchar")]
        [StringLength(128)]
        public string CategoryName { get; set; }

        [Column(TypeName = "int")]
        public int ParentId { get; set; }

        [Column(TypeName = "bit")]
        public bool IsActive { get; set; }

        public override T_ProductCategory Find(System.Linq.Expressions.Expression<Func<T_ProductCategory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.ProductCategory.FirstOrDefault(where);
                if (item != null)
                {
                    this.Id = item.Id;
                    this.CategoryName = item.CategoryName;
                    this.ParentId = item.ParentId;
                    this.IsActive = item.IsActive;
                    
                    return this;
                }
                return null;
            }
        }
        public override T_ProductCategory Find(string key)
        {
            int id = int.Parse(key);
            return Find(c => c.Id == id);
        }
        public override bool Any(System.Linq.Expressions.Expression<Func<T_ProductCategory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.ProductCategory.Any(where);
            }
        }

        public override T_ProductCategory FindLast(System.Linq.Expressions.Expression<Func<T_ProductCategory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.ProductCategory.OrderByDescending(c=>c.Id).FirstOrDefault(where);
                if (item != null)
                {
                    this.Id = item.Id;
                    this.CategoryName = item.CategoryName;
                    this.ParentId = item.ParentId;
                    this.IsActive = item.IsActive;

                    return this;
                }
                return null;
            }
        }
    }
}
